package com.nbcio.iot.listener;

import com.nbcio.iot.service.IotDataCollectionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 应用关闭监听器
 * 确保在应用关闭时正确停止所有服务
 *
 * @author nbacheng
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ApplicationShutdownListener {

    private final IotDataCollectionService dataCollectionService;

    @EventListener(ContextClosedEvent.class)
    public void onApplicationShutdown() {
        log.info("[SHUTDOWN] 应用正在关闭，停止 IoT 服务...");
        
        try {
            // 停止数据采集服务
            dataCollectionService.stop();
            log.info("[SHUTDOWN] IoT 服务已停止");
        } catch (Exception e) {
            log.error("[SHUTDOWN] 停止 IoT 服务时发生错误: {}", e.getMessage());
        }
    }
}
